package br.com.manutencao.repositories;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.manutencao.entities.Peca;

public class PecaRepository implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	private EntityManager em = Persistence.createEntityManagerFactory("jsf")
			.createEntityManager();

	public void adiciona(Peca peca) {
		em.getTransaction().begin();
		em.persist(peca);
		em.getTransaction().commit();
	}
	
	public void altera(Peca peca){
		em.getTransaction().begin();
		em.merge(peca);
		em.getTransaction().commit();
	}
	
	public void delete(Peca peca){
		em.getTransaction().begin();
		em.remove(peca);
		em.getTransaction().commit();
	}
	
	@SuppressWarnings("all")
	public Collection<Peca> buscaTodos(){
		Collection<Peca> pecas = new ArrayList<Peca>();
		
		em.getTransaction().begin();
		Query query = em.createNamedQuery("Peca.findAll");
		pecas = query.getResultList();
		em.getTransaction().commit();
		
		return pecas;
	}
	
	public Peca buscaPorId(int id){
		em.getTransaction().begin();
		Peca peca = em.find(Peca.class, id);
		em.getTransaction().commit();

		return peca;
	}
}
